package com.only4play.utils.converter;

import com.only4play.common.PasswordGenerator;
import com.only4play.common.utils.CommonUtils;
import com.only4play.constant.CommonConstant;
import com.only4play.domain.entity.UserPersonEntity;
import com.only4play.domain.entity.UserPersonalAccountEntity;
import com.only4play.dto.PersonRegisterDto;
import com.only4play.vo.UserPersonAccountVo;
import com.only4play.vo.UserPersonVo;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * @author liyuncong
 * @version 1.0
 * @file UserPersonConverter
 * @brief 用户数据转换器
 * @details 用户数据转换器
 * @date 2023-11-18
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2023-11-18               liyuncong          Created
 */
@Component
public class UserPersonConverter {

    public UserPersonEntity fromRegisterDto(PersonRegisterDto registerDto) {
        final UserPersonEntity entity = new UserPersonEntity();
        entity.setUsername(registerDto.getUsername());
        return entity;
    }

    public UserPersonalAccountEntity fromRegisterDto(
        PersonRegisterDto registerDto, PasswordGenerator passwordGenerator, PasswordEncoder passwordEncoder) {
        final String salt = RandomStringUtils.random(CommonConstant.SALT_LENGTH, true, true);
        final String password = passwordGenerator.generate(registerDto.getLoginUsername(), registerDto.getLoginPassword(), salt, passwordEncoder);
        final UserPersonalAccountEntity entity = new UserPersonalAccountEntity();
        entity.setAlias(registerDto.getUsername());
        entity.setLoginUsername(registerDto.getLoginUsername());
        entity.setLoginPassword(password);
        entity.setLoginPasswordSalt(salt);
        return entity;
    }

    public UserPersonAccountVo toUserPersonAccountVo(UserPersonalAccountEntity entity) {
        UserPersonAccountVo accountVo = new UserPersonAccountVo();
        UserPersonVo personVo = new UserPersonVo();
        personVo.setId(entity.getPerson().getId());
        personVo.setUsername(entity.getPerson().getUsername());
        accountVo.setLoginUsername(entity.getLoginUsername());
        accountVo.setPersonVo(personVo);
        return accountVo;
    }
}
